package com.fafu.forum.controller;

import com.fafu.forum.common.AppResult;
import com.fafu.forum.common.ResultCode;
import com.fafu.forum.config.AppConfig;
import com.fafu.forum.exception.ApplicationException;
import com.fafu.forum.model.Article;
import com.fafu.forum.model.Board;
import com.fafu.forum.model.User;
import com.fafu.forum.services.IArticleService;
import com.fafu.forum.services.IBoardService;
import com.fafu.forum.services.IUserService;
import com.mysql.cj.PreparedQuery;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.session.StandardSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private IBoardService boardService;
    @Autowired
    private IArticleService articleService;

    /**
     * 发布新帖子
     * @param boardId 板块 id
     * @param title 文章标题
     * @param content 文章内容
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create (HttpServletRequest request,
                             @ApiParam("板块Id") @RequestParam("boardId") @NonNull Long boardId,
                             @ApiParam("文章标题") @RequestParam("title") @NonNull String title,
                             @ApiParam("文章内容") @RequestParam("content") @NonNull String content) {
        // 验证用户是否被禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 用户被禁言
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 板块的校验
        Board board = boardService.selectById(boardId);
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_BOARD_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_NOT_EXISTS);
        }
        // 封装文章对象
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        // 调用 service 层
        articleService.create(article);
        return AppResult.success();
    }

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId (@ApiParam("板块Id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> articles;
        if (boardId == null) {
            // 查询所有
            articles = articleService.selectAll();
        } else {
            // 查询对应板块的消息
            articles = articleService.selectAllByBoardId(boardId);
        }
        if (articles == null) {
            // 如果结果集为空, 创建一个空集合
            articles = new ArrayList<>();
        }


        return AppResult.success(articles);
    }


    @ApiOperation("根据帖子 Id 获取详细信息")
    @GetMapping("/details")
    public AppResult<Article> getDetails (HttpServletRequest request,
                                          @ApiParam("帖子Id") @RequestParam(value = "id") @NonNull Long id) {
        // 从 session 中获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        // 调用 service 层
        Article article = articleService.selectDetailById(id);
        // 判断是否为空
        if (article == null) {
            // 返回错误信息
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        // 判断用户是否为作者
        if (user.getId() == article.getUserId()) {
            article.setOwn(true);
        }
        // 返回结果
        return AppResult.success(article);
    }

    @ApiOperation("修改帖子")
    @PostMapping("/modify")
    public AppResult modify (HttpServletRequest request,
                             @ApiParam("帖子Id") @RequestParam(value = "id") @NonNull Long id,
                             @ApiParam("帖子标题") @RequestParam(value = "title") @NonNull String title,
                             @ApiParam("帖子正文") @RequestParam(value = "content") @NonNull String content) {
        // 获取当前登录的用户
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 检验用户状态, 是否被禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 校验帖子是否有效
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断用户是不是作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 判断帖子的状态
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);

        }
        // 调用 service 层
        articleService.modify(id,title,content);
        // 打印日志
        log.info("帖子更新成功. Article id = " + article.getId() + " User id = " + article.getUserId());
        // 返回正确的响应
        return AppResult.success();
    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp (HttpServletRequest request,
                               @ApiParam("帖子Id") @RequestParam(value = "id") @NonNull Long id) {
        // 校验用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户是否被禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 校验帖子是否有效
        if (article == null) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }

        // 判断帖子的状态
        if (article.getState() == 1 || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);

        }
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    @ApiOperation("删除帖子")
    @PostMapping("/delete")
    public AppResult deleteById (HttpServletRequest request,
                                 @ApiParam("帖子Id") @RequestParam(value = "id") @NonNull Long id) {
        // 校验用户的状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户是否被禁言
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 查询帖子详情
        Article article = articleService.selectById(id);
        // 校验帖子是否有效
        if (article == null ||  article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 判断用户是不是作者
        if (user.getId() != article.getUserId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.deleteById(id);
        // 返回操作成功
        return AppResult.success();
    }

    @ApiOperation("获取用户的帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request,
                                     @ApiParam("用户Id") @RequestParam(value = "userId", required = false) Long userId) {
        // 如果 UserId 为空 从 session 中获取当前用户登录的 id
        if (userId == null) {
            // 获取 session
            HttpSession session = request.getSession(false);
            // 获取 user 对象
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        // 调用 service 层
        List<Article> articles = articleService.selectByUserId(userId);
        // 返回结果
        return AppResult.success(articles);
    }
}
